import router from "koa-router";
import { cloneDeep, isEmpty } from "lodash";
import {
  deleteData,
  getData,
  getDataByExcel,
  setData,
} from "../controller/data-set";
import { ErrorRes } from "../res-model";

const dataSetRouter = new router({
  prefix: `/api/data`,
});

/**
 * 设置数据集
 */
dataSetRouter.post("/:uuid/:sheet", async (ctx) => {
  const { uuid, sheet } = ctx.params;
  const data = ctx.request.body;

  if (uuid == null || sheet == null || isEmpty(data)) {
    ctx.status = 404;
    ctx.body = new ErrorRes({ code: 12345, message: "参数缺失" });
    return;
  }

  ctx.body = await setData(uuid, sheet, data);
});

/**
 * 获取数据集
 */
dataSetRouter.get("/:uuid", async (ctx) => {
  const { uuid } = ctx.params;
  if (uuid == null) {
    ctx.status = 404;
    ctx.body = new ErrorRes({ code: 12345, message: "参数缺失" });
    return;
  }
  // ctx.set("Content-type", "application/json");
  ctx.body = await getData(uuid);
});

dataSetRouter.get("/excel/:uuid", async (ctx) => {
  const { uuid } = ctx.params;
  if (uuid == null) {
    ctx.status = 404;
    ctx.body = new ErrorRes({ code: 12345, message: "参数缺失" });
    return;
  }
  ctx.set("Content-disposition", "attachment;filename=data.xlsx");
  ctx.set(
    "Content-type",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  );
  ctx.body = await getDataByExcel(uuid);
});

/**
 * 清空数据集
 */
dataSetRouter.delete("/:uuid", async (ctx) => {
  const { uuid } = ctx.params;
  const { sheet } = ctx.query;

  if (uuid == null) {
    ctx.status = 404;
    ctx.body = new ErrorRes({ code: 12345, message: "参数缺失" });
    return;
  }

  ctx.body = await deleteData(uuid, (sheet as string | undefined) ?? null);
});

export default dataSetRouter;
